import base64
import hashlib
import hmac
import json
import requests
import sys
import time
import urllib


class DingTalkAlarm:
    def __init__(self, access_token, secret):
        self.webhook_url = "https://oapi.dingtalk.com/robot/send?access_token={}".format(access_token)
        self.secret = secret

    def _signature_url(self):
        timestamp = str(round(time.time() * 1000))
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        post_url = "{}&timestamp={}&sign={}".format(self.webhook_url, timestamp, sign)
        return post_url

    def _send_message(self, title, content, mention_all):
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }

        message = {
            "msgtype": "markdown",
            "markdown": {
                "title": "{}".format(title),
                "text": "{}".format(content)
            },
            "at": {
                "isAtAll": mention_all
            }
        }

        info = requests.post(url=self._signature_url(), data=json.dumps(message), headers=header)

        if json.loads(info.text)['errmsg'] == "ok":
            print("发送成功!")
        else:
            print(json.loads(info.text))

    def send_alert(self, title, content, mention_all):
        self._send_message(title, content, mention_all)


if __name__ == "__main__":
    # 群机器人access_token
    access_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    # 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
    secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    # 需要发送的消息
    content = "hello world"
    # 是否@所有人,是输入True否则False
    mention_all = False

    # 创建DingTalkAlarm实例
    dingtalk_alarm = DingTalkAlarm(access_token, secret)

    # 调用send_alert传入需要传递的参数发送消息
    dingtalk_alarm.send_alert(content, mention_all)
